package we3d.rasterizer 
{
	import we3d.View3d;
	import we3d.mesh.Face;
	import we3d.material.Surface;
	import we3d.core.Camera3d;
	import we3d.scene.LightGlobals;
	import we3d.scene.SceneLight;
	import we3d.math.Matrix3d;
	
	public class RasterizerLight extends Rasterizer
	{
		public function RasterizerLight () {}
		
		public function getLightValueW (ux:Number, uy:Number, uz:Number, cx:Number, cy:Number, cz:Number, lightGlobals:LightGlobals) :int {
			
			var v:Number;
			var lightList:Array = lightGlobals.lightList;
			var L:int = lightList.length;
			var r:int = lightGlobals._sar;
			var g:int = lightGlobals._sag;
			var b:int = lightGlobals._sab;
			var gv:Matrix3d;
			var ang:Number;
			var lght:SceneLight;
			var r90:Number = Math.PI/2;
			var d:Number=1;
			var m:Number;
			var x:Number;
			var y:Number;
			var z:Number;
			
			for(var i:int=0; i<L; i++) {
				lght = lightList[i];
				gv = lght.transform.gv;
				
				if(lght.directional) {
					/*
					if(lght.radius > 0) {
						x = gv.m - cx;
						y = gv.n - cy;
						z = gv.o - cz;
						m = Math.sqrt(x*x + y*y + z*z);
						if(m > lght.radius) continue;
						d = (1-m/lght.radius) * lght.intensity;
					}else{
						d = lght.intensity;
					}*/
					ang = Math.acos(gv.i*ux + gv.j*uy + gv.k*uz);
					d = lght.intensity;
				}
				else{
					x = gv.m - cx;
					y = gv.n - cy;
					z = gv.o - cz;
					
					m = Math.sqrt(x*x + y*y + z*z); 
					
					if(lght.radius > 0) {
						if(m > lght.radius) continue;
						d = (lght.intensity*1000)/(m*m);
						//d = (1-m/lght.radius) * lght.intensity
					}else{
						d = lght.intensity;
					}
					
					x /= -m; y /= -m; z /= -m;
					ang = Math.acos(x*ux + y*uy + z*uz);
				}
				
				if(ang >= 0 && ang < r90) {
					
					v = d*(r90-ang);
						
					r += lght.r*v;
					g += lght.g*v;
					b += lght.b*v;
				}
				
				
			}
			
			if(r>255) r = 255;
			if(g>255) g = 255;
			if(b>255) b = 255;
			return r << 16 | g << 8 | b;
		}
		
		public function scaleColor (c1:int, c2:int, luminosity:Number, diffuse:Number) :int {
			var rc:int = (c1>>16&255)+9;
			var r:int = (rc * (c2>>16&255)/40)*diffuse;
			r += rc*luminosity;
			if(r > 255) r = 255; 
			
			var gc:int = (c1>>8&255)+9;
			var g:int = (gc * (c2>>8&255)/40)*diffuse;
			g += gc*luminosity;
			if(g > 255) g = 255; 
			
			var bc:int = (c1&255)+9;
			var b:int = (bc * (c2&255)/40)*diffuse;
			b += bc*luminosity;
			if(b > 255) b = 255; 
			
			return r << 16 | g << 8 | b;
		}
		
		public function initLights (cf:Number, c:Camera3d) :void {
			/*var lightList:Array = we.lightList;
			var L:int = lightList.length;
			for(var i:int=0; i<L; i++) {
				lightList[i].transform.initFrame(cf);
			}*/
		}
		
		
	}
}